//
//  SignatureView.swift
//  ptbuy
//
//  Created by MyMac on 2024/11/25.
//

/*
  电子签名工具页面
 */

import SwiftUI

struct SignatureView: View {
    @State private var path = Path()
    @State private var previousPoint: CGPoint? = nil
    @State private var image: Image? = nil
    // 调整签名图片的大小
    @State private var signatureImageSize: CGFloat = 200
    @State private var isAlert = false
    @State private var isFailAlert = false
    
    @Binding var clientSignPath:String
    
    @Environment(\.presentationMode) var presentationMode
    @EnvironmentObject var appDelegate: AppDelegate // 引用 AppDelegate
    
    var body: some View {
        VStack{
           
            Spacer()
            HStack {
                
                //返回
                Button(action:{
                    path = Path()
                    presentationMode.wrappedValue.dismiss()
                }) {
                    Text("返回").padding().frame(
                        maxWidth: .infinity,
                        alignment: .center
                    )
                       
                }
                .overlay(
                    RoundedRectangle(
                        cornerRadius: 8
                    )
                    .stroke(
                        Color.black,
                        lineWidth: 0.5
                    ) // 设置边框
                ).edgesIgnoringSafeArea(
                    .all
                ) // 忽略安全区域，使视图覆盖整个屏幕
                .cornerRadius(
                    8
                ) // 设置最大宽高为无穷，确保视图覆盖全屏
                
                // 清除按钮，清除签名
                Button(action:{
                    path = Path()
                }) {
                    Text("清楚").padding().frame(
                        maxWidth: .infinity,
                        alignment: .center
                    )
                       
                }
                .overlay(
                    RoundedRectangle(
                        cornerRadius: 8
                    )
                    .stroke(
                        Color.black,
                        lineWidth: 0.5
                    ) // 设置边框
                ).edgesIgnoringSafeArea(
                    .all
                ) // 忽略安全区域，使视图覆盖整个屏幕
                .cornerRadius(
                    8
                ) // 设置最大宽高为无穷，确保视图覆盖全屏
                
                // 保存按钮，将签名转换为图像
                Button(action:{
                    if path.isEmpty{
                        isAlert = true
                    }else{
                        let myBack =  saveSignature()
                        if myBack != ""{
                            presentationMode.wrappedValue.dismiss()
                        }else{
                            isFailAlert = true
                        }
                    }
                }) {
                    Text("保存").padding().frame(
                        maxWidth: .infinity,
                        alignment: .center
                    )
                       
                }.alert("请签名后保存",isPresented:$isAlert){
                    Button("关闭", role: .cancel) {
                        isAlert = false
                    }
                }.alert("保存签名失败，请返回重试",isPresented:$isFailAlert){
                    Button("关闭", role: .cancel) {
                        isFailAlert = false
                    }
                }
                .overlay(
                    RoundedRectangle(
                        cornerRadius: 8
                    )
                    .stroke(
                        Color.black,
                        lineWidth: 0.5
                    ) // 设置边框
                ).edgesIgnoringSafeArea(
                    .all
                ) // 忽略安全区域，使视图覆盖整个屏幕
                .cornerRadius(
                    8
                ) // 设置最大宽高为无穷，确保视图覆盖全屏
                
            }
            
            VStack {
                // 绘制区域，用户可以在这里签名
                Canvas { context, size in
                    context.stroke(path, with: .color(.black), lineWidth: 2)
                }
                .frame(width: UIScreen.main.bounds.width - 40, height: 200)
                .border(Color.black)
                .gesture(
                    DragGesture(minimumDistance: 0)
                        .onChanged { value in
                            // 处理手势变化
                            if let _previousPoint = previousPoint {
                                path.addLine(to: value.location)
                            } else {
                                path.move(to: value.location)
                            }
                            self.previousPoint = value.location
                        }
                        .onEnded { _ in
                            // 手势结束后，重置上一个点
                            previousPoint = nil
                        }
                )
                // 显示已生成的签名图像
                if let image = image {
                    image
                        .resizable()
                        .scaledToFit()
                        .frame(width: .infinity, height: signatureImageSize)
                        .padding()
                }
                
                
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .edgesIgnoringSafeArea(.all)
            .padding()
            .onAppear {
                // 强制横屏
                appDelegate.lockOrientation(.landscape)
            }.onDisappear {
                // 恢复屏幕旋转
                appDelegate.unlockOrientation()
            }
            .navigationTitle("客户签名")
            .navigationBarBackButtonHidden(true)
        }
        
    }
    
    // 保存签名为图像
    func saveSignature()->String {
        var back:String = "";
        let size = CGSize(width: UIScreen.main.bounds.width - 40 , height: 200)
        let renderer = UIGraphicsImageRenderer(size: size)
        
        let image = renderer.image { ctx in
            // 绘制路径到上下文
            UIColor.white.setFill()
            //            ctx.fill(CGRect(x: 0, y: 0, width: 300, height: 100))
            ctx.fill(CGRect(origin: .zero, size: size))
            UIColor.black.setStroke()
            ctx.cgContext.addPath(path.cgPath)
            ctx.cgContext.setLineWidth(2)
            ctx.cgContext.strokePath()
        }
                
        // 保存图像到文件系统
        if let data = image.pngData() {
            clientSignPath = UUID().uuidString
                .replacingOccurrences(of: "-", with: "")+".jpg"
            let filename = Utils.getDocumentsDirectory().appendingPathComponent(
                clientSignPath
            )
            do {
                try data.write(to: filename)
                print("签名已保存到: \(filename)")
                // 返回上一页
                back = "success"
            } catch {
                print("保存图像时出错: \(error)")
            }
        }
        return back;
    }
}
